package service

import (
	"strconv"
	"sysu-giep/internal/database/models"
	"time"

	"gorm.io/gorm"
)

type NotificationService struct {
	db *gorm.DB
}

func NewNotificationService(db *gorm.DB) *NotificationService {
	return &NotificationService{
		db: db,
	}
}

// GetNotificationsById 根据用户ID获取通知列表
func (s *NotificationService) GetNotificationsById(id uint, page int, size int) ([]map[string]interface{}, int64, error) {
	var notifications []map[string]interface{}
	var total int64

	query := s.db.Model(&models.Notification{}).Where("user_id = ?", id)
	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}
	// 分页查询
	offset := (page - 1) * size
	if err := query.Offset(offset).
		Limit(size).
		Find(&notifications).Error; err != nil {
		return nil, 0, err
	}
	return notifications, total, nil
}

// MarkNotificationAsRead 标记通知为已读
func (s *NotificationService) MarkNotificationAsRead(UserId uint, str string) error {
	notificationID, err := strconv.Atoi(str)
	if err != nil {
		return err
	}
	// 检查通知是否存在
	var notification models.Notification
	if err := s.db.Where("id = ? AND user_id = ?", notificationID, UserId).First(&notification).Error; err != nil {
		return err
	}
	// 更新通知状态
	notification.IsRead = true
	CurTime := time.Now()
	notification.ReadAt = &CurTime
	if err := s.db.Save(&notification).Error; err != nil {
		return err
	}
	return nil
}

// GetUnreadNotificationCount 获取未读通知数量
func (s *NotificationService) GetUnreadNotificationCount(id uint) (int64, error) {
	var count int64
	if err := s.db.Model(&models.Notification{}).Where("user_id = ? AND is_read = ?", id, false).Count(&count).Error; err != nil {
		return 0, err
	}
	return count, nil
}
